const AUTHPAGE = '/pages/login/index'

const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}


/**
 * 封装微信request
 */
function request(url, data = {}, method = "POST", header = "application/x-www-form-urlencoded") {
  var api_token = wx.getStorageSync("api_token");
  data.api_token = api_token;
  wx.showLoading({
    title: '加载中...',
  });
  return new Promise(function (resolve, reject) {
    wx.request({
      url: url,
      data: data,
      method: method,
      header: {
        'Content-Type': header,
        'Accept': 'application/json'
      },
      success: function (res) {
        wx.hideLoading();
        if (res.statusCode == 200) {
          getApp().globalData.reqState = 0;
          resolve(res.data);
        } else {
          if (res.statusCode == 401) {
            getApp().globalData.reqState = 1;
            wx.navigateTo({
              url: AUTHPAGE,
            })
          } else {
            reject(res);
          }
        }
      },
      fail: function (err) {
        reject(err)
      }
    })
  });
}

module.exports = {
  formatTime,
  request,
}
